﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Djs.HW.Util.MsCommPort
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
			this._IrReceiver = new IrReceiver(20m);
			this._IrReceiver.IrReceivedPacket += new IrReceiver.IrReceivedPacketEventHandler(_IrReceiver_IrReceivedPacket);
			this._OuterInit();
			this._ReadComList();
		}

		private void _ReadComList()
		{
			this._ComPortCombo.Items.Clear();
			this._ComPortCombo.DropDownStyle = ComboBoxStyle.DropDownList;
			List<string> ports = new List<string>(System.IO.Ports.SerialPort.GetPortNames());
			ports.Sort();
			foreach (string port in ports)
				this._ComPortCombo.Items.Add(port);
			this._ComPortCombo.SelectedIndex = 0;

		}
		private void _StartBtn_Click(object sender, EventArgs e)
		{
			string portName = this._ComPortCombo.Text;
			this._IrReceiver.StartReceive(portName);
		}
		void _IrReceiver_IrReceivedPacket(object sender, IrReceiver.PacketReceivedEventArgs e)
		{
			this._LogGraph.Packet = e.ReceivedPacket.Clone();
			this._LogGraph.Invalidate();
			this._Packet = e.ReceivedPacket.Clone();
			this._ShowPacketText();
			this._AddPacket(e.ReceivedPacket);
		}
		private delegate void CallVoid();
		private void _ShowPacketText()
		{
			if (this.InvokeRequired)
				this.BeginInvoke(new CallVoid(_ShowPacketText));
			else
				this._ResultTxt.Text = this._Packet.GetTimeResult();
		}

		private IrReceiver _IrReceiver;
		IrReceiver.ReceivedPacket _Packet;

		private void _CloseBtn_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void _ComPortCombo_SelectedIndexChanged(object sender, EventArgs e)
		{
		}

		private void Form1_FormClosed(object sender, FormClosedEventArgs e)
		{
		}

		private void _Outer_SizeChanged(object sender, EventArgs e)
		{
			_Inner.Width = _Outer.Width - _InOutDiff;
		}
		private void _OuterInit()
		{
			_InOutDiff = _Outer.Width - _Inner.Width;
			_Inner.Height = 0;
		}
		private int _InOutDiff;
		private List<LogAnalyzerGraph> _Graphs;
		private void _AddPacket(IrReceiver.ReceivedPacket packet)
		{
			if (_Inner.InvokeRequired)
				// Invokace threadu ownera:
				_Inner.BeginInvoke(new Action<IrReceiver.ReceivedPacket>(_AddPacket), packet);
			else
			{
				// Přidání grafu pro paket:
				LogAnalyzerGraph graph = new LogAnalyzerGraph();

				_Inner.Controls.Add(graph);
				graph.Bounds = new Rectangle(0, _Inner.Height, _Inner.Width, 30);
				_Inner.Height = _Inner.Height + graph.Height;
				graph.Packet = packet;
			}
		}
	}

}
